import networkx as nx
import numpy as np
N = 1000
# 设置随机数种子
np.random.seed(1)

def write2File(G,filename,n):
    """
    将图G输出为文本数据,格式为
    u,v,weight
    """
    with open(filename, 'w') as f:
        f.write(f"{n}\n") #首先输出矩阵的大小,从0到n-1个节点
        for u, v, data in G.edges(data=True):
            weight = data['weight']
            f.write(f"{u},{v},{weight}\n")
        f.write('-'*10)
        f.write('\n')
        source = 0
        lengths = nx.single_source_dijkstra_path_length(G, source)
        x = np.full(n,10000) #两端都用10000填充
        for key in lengths:
            x[key] = lengths[key]
        for i in range(n):
            f.write(f"{i},{x[i]}\n")
        
            

def createG(n,p,seed):
    """
    创建图G
    """
    G = nx.erdos_renyi_graph(n, p,directed = True,seed = seed)
    # 为每条边分配随机整数权重
    for (u, v) in G.edges():
        G.edges[u, v]['weight'] = np.random.randint(1, 100)  # 权重范围为1到10的整数
    return G



if __name__ == "__main__":
    for i in range(N):
        n = np.random.randint(5,30)
        p = 0.3
        seed = np.random.randint(1, 1000000000)
        G = createG(n, p, seed)
        filename = "DijkstraData/graph_" + str(i) + ".txt"
        write2File(G, filename,n)


